import React, {memo, useEffect, useLayoutEffect, useRef, useState} from "react";
import {Terminal} from 'xterm';
import {FitAddon} from 'xterm-addon-fit';
import 'xterm/css/xterm.css';
import styles from './index.module.scss';

interface Iprops {
  id: any
  vId: string
  activeId: string
}

const WebTerminal: React.FC<Iprops> = (props: Iprops) => {

  console.log('--------- WebTerminal-----------')

  const container = useRef<any>();
  // const [term, setTerm] = useState(new Terminal());
  // const [fitAddon] = useState(new FitAddon());

  useEffect(() => {


  }, [])

  useEffect(() => {
    if (props.vId === props.activeId) {
      // setTimeout(() => term.focus())
    }
  }, [props.activeId])

  // dom 的相关操作放到 useLayouteEffect 中去，避免导致闪烁
  useLayoutEffect(() => {
    const term = new Terminal({
      rendererType: "canvas", //渲染类型
      convertEol: true, //启用时，光标将设置为下一行的开头
      scrollback: 10, //终端中的回滚量
      disableStdin: false, //是否应禁用输入
      cursorBlink: true, //光标闪烁
      theme: {
        foreground: 'yellow', //字体
        background: '#2b2b2b', //背景色
        cursor: 'help',//设置光标
      },
      fontFamily: 'Source Code Pro, Courier New, Courier, Monaco, monospace, PingFang SC, Microsoft YaHei',
    });

    const fitAddon = new FitAddon()
    term.loadAddon(fitAddon);
    term.open(container.current);
    // term.open(document.getElementById('terminal'));
    fitAddon.fit()

    term.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ');
    term.writeln('Welcome to xterm.js')
    term.writeln('This is a local terminal emulation, without a real terminal in the back-end.')
    term.writeln('Type some keys and commands to play around.')
    term.writeln('')
    // term.clear()
    // fitTerminal()
  }, [])

 /* function fitTerminal() {
    if (props.vId === props.activeId) {
      const dims = fitAddon.proposeDimensions();
      if (!dims || !term || !dims.cols || !dims.rows) return;
      if (term.rows !== dims.rows || term.cols !== dims.cols) {
        console.log('--------- useLayoutEffect-----------')
        term.clear()
        term.resize(dims.cols, dims.rows);
      }
    }
  }*/

  function _read_as_text(data: any) {
    const reader = new window.FileReader();
    // reader.onload = () => term.write(String(reader.result));
    // reader.readAsText(data, 'utf-8')
  }

  return (
    <div className={styles.termContainer}>
      <div className={styles.terminal} ref={container}/>
    </div>
  )
}

export default memo(WebTerminal)
